package ar.com.ctrln.view.dashboard.administracion.cliente;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.VariableResolver;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Textbox;

import ar.com.ctrln.control.administracion.cliente.ConsultarContacto;
import ar.com.ctrln.persistence.model.contacto.Contacto;
import ar.com.ctrln.view.ui.comportamientoVentana.AbstractMinimizarVentana;

@VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class)
public class ConsultarContactoController extends AbstractMinimizarVentana {

	private static final long serialVersionUID = 5862815344097176511L;

	@WireVariable
	private ConsultarContacto consultarContacto;

	private List<Contacto> contactos;

	@Wire
	private Listbox lbContactos;

	@Wire("#txtFilter")
	private Textbox txtFilter;

	@Wire
	private Label footer_label;

	@Override
	public void doAfterCompose(Component comp) throws Exception {

		super.doAfterCompose(comp);
		contactos = consultarContacto.listarContactos();

		ListModelList<Contacto> modelo = new ListModelList<Contacto>();

		modelo.addAll(contactos);

		lbContactos.setModel(modelo);

	}

	public ListModel<Contacto> getConsultarContactos() {
		contactos = consultarContacto.listarContactos();
		return new ListModelList<Contacto>(contactos);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Listen("onChanging = #txtFilter")
	public void getFilter(Event event) {
		((Textbox) event.getTarget())
				.setValue(((org.zkoss.zk.ui.event.InputEvent) event).getValue());
		lbContactos.setModel(new ListModelList(getFilterBy(
				txtFilter.getValue(), contactos)));
		if (lbContactos.getItemCount() > 0) {
			footer_label.setValue("");
			footer_label.setValue("Un total de " + lbContactos.getItemCount()
					+ " Contactos");
		} else {
			footer_label.setValue("Ningun Resultado...");
			footer_label.setValue("");
		}
		((Textbox) event.getTarget()).setFocus(true);
	}

	public static List<Contacto> getFilterBy(String condicion,
			Collection<Contacto> contactos) {
		List<Contacto> data = new ArrayList<Contacto>();
		for (Iterator<Contacto> i = contactos.iterator(); i.hasNext();) {
			Contacto tmp = i.next();
			if (tmp.getNombre().toLowerCase()
					.indexOf(condicion.trim().toLowerCase()) >= 0
					|| tmp.getApellido().toLowerCase()
							.indexOf(condicion.trim().toLowerCase()) >= 0) {
				data.add(tmp);
			}
		}
		return data;
	}
}
